import { createReducer } from 'reduxsauce'
import {
  LOGIN_WEIXIN,
  REQUEST_AUTH_CODE,
  LOGIN_OR_REGISTER_BY_PHONE,
  UPDATE_NETWORK_STATUS,
  WECHAT_LOGIN,
  CHECK_STATUS,
  SET_LOGIN_SUCCESS_INFO,
  LOGOUT_USER,
  GET_SYSTEM_CONFIG
} from '@ACTIONS/auth'
import { getPlatform } from '@UTILS/common'
import { AuthStateITF } from '@REDUXITF/auth'
import { UserITF } from '@INTERFACES/user'

const isCheckStatus = true
const { isWX } = getPlatform()

const INITIAL_STATE: AuthStateITF = {
  ActionTokenId: '',
  user: null,
  isConnected: true,
  isDisabledConsultation: isCheckStatus && isWX,
  lastSetLoginInfoTime: undefined,
  loginSuccess: undefined,
  loadingSystemConfig: true,
  systemConfig: null
}

export default createReducer(INITIAL_STATE, {
  [LOGIN_WEIXIN.SUCCESS]: (state, { result }: { result: UserITF }) => ({
    ...state,
    user: result,
  }),
  [WECHAT_LOGIN.SUCCESS]: (state, { user }: { user: UserITF }) => ({
    ...state,
    user,
  }),
  [REQUEST_AUTH_CODE.SUCCESS]: (state, { ActionTokenId }: { ActionTokenId: string }) => ({
    ...state,
    ActionTokenId,
  }),
  [LOGIN_OR_REGISTER_BY_PHONE.SUCCESS]: (state, { result }: { result: UserITF }) => ({
    ...state,
    ActionTokenId: '',
    user: result,
  }),
  [UPDATE_NETWORK_STATUS.REQUEST]: (state, { isConnected }: { isConnected: boolean }) => ({
    ...state,
    isConnected
  }),
  [CHECK_STATUS.SUCCESS]: (state, { DisabledConsulation }) => ({
    ...state,
    isDisabledConsultation: DisabledConsulation
  }),
  [GET_SYSTEM_CONFIG.REQUEST]: state => ({
    ...state,
    loadingSystemConfig: true
  }),
  [GET_SYSTEM_CONFIG.SUCCESS]: (state, { result }) => ({
    ...state,
    loadingSystemConfig: false,
    systemConfig: result,
  }),
  [SET_LOGIN_SUCCESS_INFO.REQUEST]: (state, { loginSuccess }) => ({
    ...state,
    lastSetLoginInfoTime: new Date().getTime(),
    loginSuccess
  }),
  [LOGOUT_USER.SUCCESS]: state => ({
    ...state,
    lastSetLoginInfoTime: undefined,
    loginSuccess: undefined
  }),
})
